#!/bin/bash
# 检查是否安装教程编译器
# 检查是否已经编译好linux内核

# 创建linux根文件系统
# 使用qemu加载linux内核

# usage:
#   source ~/vimrc/embedded/create_arm_rootfs.sh  create

if test ! -d "/usr/arm-linux-gnueabihf/lib"; then
  echo "请安装交叉编译器"
  return
fi

ROOTFS_PATH=~/study/qemu/
if test ! -e $ROOTFS_PATH/linux/arch/arm/boot/zImage; then
    echo "没有zImage, 请编译arm架构linux内核"
    return
fi

file_info=$(file $ROOTFS_PATH/busybox/_install/bin/busybox)
# 判断busybox编译的结果是不是ARM架构
if ! echo $file_info | grep -iq "ARM\|arm"; then
  echo "Please compile busybox for ARM32"
  return
fi


if [ "$1" == "create" ]; then 
    # 如果rootfs目录存在
    if test -d "$ROOTFS_PATH/rootfs"; then
        sudo rm -rf $ROOTFS_PATH/rootfs
    fi
    mkdir $ROOTFS_PATH/rootfs
    mkdir -p $ROOTFS_PATH/rootfs/{dev,lib,mnt,etc/init.d,sysconfig}
    sudo cp -arf $ROOTFS_PATH/busybox/_install/* $ROOTFS_PATH/rootfs/  
    sudo cp -arf /usr/arm-linux-gnueabihf/lib/* $ROOTFS_PATH/rootfs/lib/
    sudo mknod $ROOTFS_PATH/rootfs/dev/tty1 c 4 1
    sudo mknod $ROOTFS_PATH/rootfs/dev/tty2 c 4 2
    sudo mknod $ROOTFS_PATH/rootfs/dev/tty3 c 4 3
    sudo mknod $ROOTFS_PATH/rootfs/dev/tty4 c 4 4
    sudo mknod $ROOTFS_PATH/rootfs/dev/console c 5 1
    sudo mknod $ROOTFS_PATH/rootfs/dev/null c 1 3

    echo '-------------------------------' > $ROOTFS_PATH/rootfs/etc/init.d/rcS
    echo 'welcome to A9 board' >> $ROOTFS_PATH/rootfs/etc/init.d/rcS
    echo '--------------------------------' >> $ROOTFS_PATH/rootfs/etc/init.d/rcS

    chmod +x $ROOTFS_PATH/rootfs/etc/init.d/rcS


    dd if=/dev/zero of=$ROOTFS_PATH/rootfs_arm.ext3 bs=1M count=32
    mkfs.ext3 $ROOTFS_PATH/rootfs_arm.ext3
    sudo mount -t ext3 $ROOTFS_PATH/rootfs_arm.ext3 /mnt -o loop
    sudo cp -r $ROOTFS_PATH/rootfs/* /mnt
    sudo umount /mnt
fi

qemu-system-arm -M vexpress-a9 -m 512M \
                    -kernel $ROOTFS_PATH/linux/arch/arm/boot/zImage \
                    -dtb $ROOTFS_PATH/linux/arch/arm/boot/dts/vexpress-v2p-ca9.dtb \
                    -nographic \
                    -append "root=/dev/mmcblk0 rw console=ttyAMA0" \
                    -sd  $ROOTFS_PATH/rootfs_arm.ext3
